package cn.juque.systemservice.service.impl;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.RandomUtil;
import cn.juque.common.base.BaseOperator;
import cn.juque.common.base.PageInfo;
import cn.juque.common.constants.MessageEnum;
import cn.juque.common.exception.AppException;
import cn.juque.systemservice.cache.SmsCache;
import cn.juque.systemservice.entity.SmsLog;
import cn.juque.systemservice.mapper.SmsLogMapper;
import cn.juque.systemservice.service.ISmsLogService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author JUQUE
 * @version 1.0.0
 * <li>simple-generator</li>
 * <li></li>
 * @date 2021-09-30 14:39:45
 **/
@Service("smsLogService")
public class SmsLogServiceImpl implements ISmsLogService {

    @Resource
    private SmsLogMapper smsLogMapper;

    @Resource
    private SmsCache smsCache;

    /**
     * 分页查询
     *
     * @param pageInfo pageInfo
     * @param smsLog   smsLog
     * @return DataGrid
     */
    @Override
    public List<SmsLog> listLogWithPage(PageInfo pageInfo, SmsLog smsLog) {
        Page<SmsLog> page = new Page<>(pageInfo.getPage(), pageInfo.getLimit());
        List<SmsLog> list = this.smsLogMapper.queryLogList(page, smsLog);
        pageInfo.setTotal(page.getTotal());
        return list;
    }

    @Override
    public SmsLog saveLog(String tel, String content, Integer codeNum, Long validateSecond, BaseOperator operator) {
        String code = null;
        if(null != codeNum) {
            code = RandomUtil.randomNumbers(codeNum);
            // 保存到缓存
            this.smsCache.put(tel, code, validateSecond);
        }
        SmsLog smsLog = new SmsLog();
        smsLog.setTel(tel);
        smsLog.setCheckCode(code);
        smsLog.setContent(CharSequenceUtil.format(content, code));
        smsLog.setCreateUserId(operator.getOperatorId());
        boolean flag = SqlHelper.retBool(this.smsLogMapper.insert(smsLog));
        if (!flag) {
            throw new AppException(MessageEnum.SYSTEM_FAIL.getCode(), "保存失败");
        }
        return smsLog;
    }

    /**
     * 校验验证码
     *
     * @param tel  手机号
     * @param code 验证码
     * @return true=成功
     */
    @Override
    public Boolean checkCode(String tel, String code) {
        if(CharSequenceUtil.isEmpty(code)) {
            return false;
        }
        String validCode = this.smsCache.get(tel);
        return code.equals(validCode);
    }
}
